<template>
    <div class="menu-container">
        <!-- 分组右键菜单 -->
        <teleport to="body">
            <transition name="context-menu">
                <ul v-show="currentContextMenu.show" :style="menuStyle" class="context-menu" @click.stop
                    @contextmenu.prevent>
                    <li @click="handleMenuClick(item.action)" v-for="item in data">
                        <el-button type="info" link :icon="getIcon(item.icon)">{{ item.actionName }}</el-button>
                    </li>
                </ul>
            </transition>
        </teleport>
    </div>
</template>

<script setup>
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

// 右键菜单相关状态
const currentContextMenu = defineModel({
    type: Object,
    default: {}
})
const props = defineProps({
    data: {
        type: Array,
        default: []
    }
})
const { data } = toRefs(props)

// 菜单项点击处理
const handleMenuClick = (action) => {
    if (!currentContextMenu.value) return
    action(currentContextMenu.value.data)
    currentContextMenu.value.show = false
}

// 点击页面其他区域关闭菜单
const handleClickOutside = (event) => {
    if (!event.target.closest('.context-menu')) {
        currentContextMenu.value.show = false
    }
}

// 菜单样式计算
const menuStyle = computed(() => ({
    left: `${currentContextMenu.value.x}px`,
    top: `${currentContextMenu.value.y}px`
}))

const getIcon = (name) => {
    for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
        if(key === name) return component
    }
}

onMounted(() => {
    window.addEventListener('click', handleClickOutside)
})

onBeforeUnmount(() => {
    window.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped lang="scss">

.context-menu {
    position: fixed;
    z-index: 3000;
    min-width: 80px;
    background: var(--el-bg-color-overlay);
    border-radius: 6px;
    padding: 6px 0;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin: 0;
    list-style: none;
    font-size: 12px;

    li {
        padding: 8px 16px;
        display: flex;
        align-items: center;
        gap: 8px;
        cursor: pointer;
        transition: all 0.2s;
        color: var(--el-text-color-regular);
    }

    li:hover {
        background-color: var(--el-color-primary-light-9);
        color: var(--el-color-primary);
    }

    .context-menu-enter-active,
    .context-menu-leave-active {
        transition: all 0.15s;
    }

    .context-menu-enter-from,
    .context-menu-leave-to {
        opacity: 0;
        transform: translateY(-10px);
    }
}
</style>